package gbackup.command;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import com.google.gdata.data.MediaContent;
import com.google.gdata.data.OutOfLineContent;
import com.google.gdata.data.media.MediaSource;
import com.google.gdata.util.ServiceException;

import core.Directory;
import core.File;
import core.Shell;
import core.Utility;

public class GetCommand extends Command {

	public GetCommand(Shell shell, String rawCommand) {
		super(shell, rawCommand);
	}

	@Override
	public void execute() {
		if (this._arguments.size() != 1) {
			this._outputPrintStream.println("Invalid Argument : [" + this._rawCommand + "]");
			return;
		}

		String fileName = this._arguments.get(0);
		Directory workingDirectory = this._shell.getWorkingDirectory();
		File targetFile = null;
		for (File f : workingDirectory.getChildern()) {
			if (!f.isFile())
				continue;
			if (!f.getName().equals(fileName))
				continue;

			targetFile = f;
		}

		if (targetFile == null) {
			this._outputPrintStream.println("File Not Found : [" + fileName + "]");
			return;
		}
		
		String exportUrl = ((OutOfLineContent) targetFile.getEntry().getContent()).getUri();
		try {
			java.io.File tmpFile = java.io.File.createTempFile("tmp_", ".zip");
			tmpFile.deleteOnExit();
//			java.io.File downloadedFile = this.downloadFile(exportUrl, this._shell.getLocalWorkingDirectory().getAbsolutePath() + File.FILE_SEPERATOR + fileName);
			java.io.File downloadedFile = this.downloadFile(exportUrl, tmpFile.getAbsolutePath());
			java.io.File unzippedFile = Utility.unzip(downloadedFile);
			java.io.File locatedFile = new java.io.File(this._shell.getLocalWorkingDirectory().getAbsolutePath() + File.FILE_SEPERATOR + fileName.substring(0, fileName.lastIndexOf(".zip")));
			
			FileInputStream fis = new FileInputStream(unzippedFile);
			FileOutputStream fos = new FileOutputStream(locatedFile);
			int c;
			while((c = fis.read()) != -1) {
				fos.write(c);
			}
			fis.close();
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
	}

	private java.io.File downloadFile(String exportUrl, String filepath) throws IOException, MalformedURLException, ServiceException {
		MediaContent mc = new MediaContent();
		mc.setUri(exportUrl);
		MediaSource ms = this._shell.getDocsService().getMedia(mc);

		InputStream inStream = null;
		FileOutputStream outStream = null;

		try {
			inStream = ms.getInputStream();
			outStream = new FileOutputStream(filepath);

			int c;
			while ((c = inStream.read()) != -1) {
				outStream.write(c);
			}
		} finally {
			if (inStream != null) {
				inStream.close();
			}
			if (outStream != null) {
				outStream.flush();
				outStream.close();
			}
		}
		
		return new java.io.File(filepath);
	}

}
